<template>
  <el-container class="layout-lr">
    <el-aside width="360px" class="p-[20px]">
      <div class="add">
        <el-tag type="primary" @click="f_AddPoint">
          <i-ep-plus class="mr-[2px] text-size-[11px] v-bottom" />添加管点类型
        </el-tag>
        <el-tag type="primary" class="ml-[20px]" @click="f_AddLine">
          <i-ep-plus class="mr-[2px] text-size-[11px] v-bottom" />添加管段类型
        </el-tag>
      </div>

      <!-- <VueDraggableNext v-model="list">
        <transition-group>
          <div v-for="item in list">{{ item.name }}</div>
        </transition-group>
      </VueDraggableNext> -->

      <el-menu :default-active="activeMenu">
        <el-sub-menu index="1">
          <template #title>
            <el-icon class="mt-[-4px]">
              <box-icon
                color="'#878a99"
                size="18px"
                name="map"
                class="mt-[4px]"
              />
            </el-icon>
            <span> 管点 </span>
          </template>
          <VueDraggableNext v-model="pointData" @end="f_DragEndPoint">
            <el-menu-item
              v-for="(element, index) in pointData"
              @click="f_ClickPointMenu(index)"
              :index="'1-' + index"
              :key="index"
            >
              <img
                v-if="element.image == 1"
                :src="deviceIcon1"
                class="device-icon menu"
              />
              <img
                v-if="element.image == 2"
                :src="deviceIcon2"
                class="device-icon menu"
              />
              <img
                v-if="element.image == 3"
                :src="deviceIcon3"
                class="device-icon menu"
              />
              <img
                v-if="element.image == 4"
                :src="deviceIcon4"
                class="device-icon menu"
              />
              <img
                v-if="element.image == 5"
                :src="deviceIcon5"
                class="device-icon menu"
              />
              <img
                v-if="element.image == 6"
                :src="deviceIcon6"
                class="device-icon menu"
              />
              <img
                v-if="element.image == 7"
                :src="deviceIcon7"
                class="device-icon menu"
              />
              <img
                v-if="element.image == 8"
                :src="deviceIcon8"
                class="device-icon menu"
              />

              <img
                v-if="element.image == 9"
                :src="deviceIcon9"
                class="device-icon menu"
              />
              <img
                v-if="element.image == 10"
                :src="deviceIcon10"
                class="device-icon menu"
              />
              <img
                v-if="element.image == 11"
                :src="deviceIcon11"
                class="device-icon menu"
              />

              <img
                v-if="element.image == 12"
                :src="deviceIcon12"
                class="device-icon menu"
              />
              <img
                v-if="element.image == 13"
                :src="deviceIcon13"
                class="device-icon menu"
              />
              <img
                v-if="element.image == 14"
                :src="deviceIcon14"
                class="device-icon menu"
              />
              <img
                v-if="element.image == 15"
                :src="deviceIcon15"
                class="device-icon menu"
              />
              <img
                v-if="element.image == 16"
                :src="deviceIcon1"
                class="device-icon menu"
              />
              <img
                v-if="element.image == 17"
                :src="deviceIcon17"
                class="device-icon menu"
              />
              <img
                v-if="element.image == 18"
                :src="deviceIcon18"
                class="device-icon menu"
              />
              <img
                v-if="element.image == 19"
                :src="deviceIcon19"
                class="device-icon menu"
              />
              <img
                v-if="element.image == 20"
                :src="deviceIcon20"
                class="device-icon menu"
              />
              {{ element.className }}
            </el-menu-item>
          </VueDraggableNext>
        </el-sub-menu>

        <el-sub-menu index="2">
          <template #title>
            <el-icon class="mt-[-4px]">
              <box-icon
                color="'#878a99"
                size="18px"
                name="sitemap"
                class="mt-[4px]"
              />
            </el-icon>
            <span> 管段 </span>
          </template>
          <VueDraggableNext v-model="lineData" @end="f_DragEndLine">
            <el-menu-item
              @click="f_ClickLineMenu(index)"
              :index="'2-' + index"
              v-for="(ele, index) in lineData"
              :key="index"
            >
              <span
                class="linePoint"
                :style="{ background: ele.image ? ele.image : '#fff' }"
              ></span>
              {{ ele.className }}</el-menu-item
            >
          </VueDraggableNext>
        </el-sub-menu>
      </el-menu></el-aside
    >
    <el-container>
      <el-main>
        <div
          v-if="
            (form.category == 1 && pointData.length) ||
            (form.category == 2 && lineData.length)
          "
        >
          <div class="title">
            设备信息

            <el-button
              @click="f_HandleSubmit"
              type="primary"
              class="ml-[20px] float-right pl-[20px!important] pr-[20px!important] h-[26px!important]"
            >
              <i-ep-plus class="mr-[2px] text-size-[11px] v-bottom" />保存
            </el-button>
            <el-button
              v-if="form.id && isDelDeviceCateGory"
              @click="f_HandleDel"
              type="danger"
              class="float-right pl-[20px!important] pr-[20px!important] h-[26px!important]"
            >
              <i-ep-delete class="mr-[2px] text-size-[11px] v-bottom" />删除{{
                form.category == 1 ? "设备" : "管段"
              }}
            </el-button>
          </div>
          <div>
            <el-form
              :model="form"
              label-width="120"
              size="small"
              label-position="left"
              class="mt-[20px]"
            >
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item
                    :label="
                      (form.category == 1 ? '设备' : '管段') + '类型名称：'
                    "
                  >
                    <el-input
                      v-model="form.className"
                      maxlength="50"
                      show-word-limit
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item
                    :label="(form.category == 1 ? '设备' : '管段') + '图例：'"
                  >
                    <div v-if="form.pClassId == 1" @click="f_SelectIconOpen">
                      <span>
                        <img
                          v-if="form.image == 1"
                          :src="deviceIcon1"
                          class="device-icon menu"
                        />
                        <img
                          v-if="form.image == 2"
                          :src="deviceIcon2"
                          class="device-icon menu"
                        />
                        <img
                          v-if="form.image == 3"
                          :src="deviceIcon3"
                          class="device-icon menu"
                        />
                        <img
                          v-if="form.image == 4"
                          :src="deviceIcon4"
                          class="device-icon menu"
                        />
                        <img
                          v-if="form.image == 5"
                          :src="deviceIcon5"
                          class="device-icon menu"
                        />
                        <img
                          v-if="form.image == 6"
                          :src="deviceIcon6"
                          class="device-icon menu"
                        />
                        <img
                          v-if="form.image == 7"
                          :src="deviceIcon7"
                          class="device-icon menu"
                        />
                        <img
                          v-if="form.image == 8"
                          :src="deviceIcon8"
                          class="device-icon menu"
                        />

                        <img
                          v-if="form.image == 9"
                          :src="deviceIcon9"
                          class="device-icon menu"
                        />
                        <img
                          v-if="form.image == 10"
                          :src="deviceIcon10"
                          class="device-icon menu"
                        />
                        <img
                          v-if="form.image == 11"
                          :src="deviceIcon11"
                          class="device-icon menu"
                        />

                        <img
                          v-if="form.image == 12"
                          :src="deviceIcon12"
                          class="device-icon menu"
                        />
                        <img
                          v-if="form.image == 13"
                          :src="deviceIcon13"
                          class="device-icon menu"
                        />
                        <img
                          v-if="form.image == 14"
                          :src="deviceIcon14"
                          class="device-icon menu"
                        />
                        <img
                          v-if="form.image == 15"
                          :src="deviceIcon15"
                          class="device-icon menu"
                        />
                        <img
                          v-if="form.image == 16"
                          :src="deviceIcon16"
                          class="device-icon menu"
                        />
                        <img
                          v-if="form.image == 17"
                          :src="deviceIcon17"
                          class="device-icon menu"
                        />
                        <img
                          v-if="form.image == 18"
                          :src="deviceIcon18"
                          class="device-icon menu"
                        />
                        <img
                          v-if="form.image == 19"
                          :src="deviceIcon19"
                          class="device-icon menu"
                        />
                        <img
                          v-if="form.image == 20"
                          :src="deviceIcon20"
                          class="device-icon menu"
                        />
                      </span>
                    </div>

                    <el-color-picker v-else v-model="form.image" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item
                    :label="
                      (form.category == 1 ? '设备' : '管段') + 'GIS编码：'
                    "
                  >
                    <el-input
                      v-model="form.classGisNo"
                      disabled
                      placeholder="点击保存生成GIS编码"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12" v-if="form.category == 1">
                  <el-form-item label="是否采集数据：">
                    <el-switch
                      v-model="form.isCollection"
                      @change="f_ChangeIsCollection"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
          <div class="title mt-[20px]">
            设备属性

            <el-tag
              @click="f_Add"
              type="primary"
              class="ml-[20px] float-right pl-[20px!important] pr-[20px!important] h-[26px!important] cursor-pointer"
            >
              <i-ep-plus class="mr-[2px] text-size-[11px] v-bottom" />添加{{
                (form.category == 1 ? "设备" : "管段") + "属性"
              }}
            </el-tag>
          </div>
          <div class="mt-[20px]">
            <el-table
              :data="form.classAttribute"
              border
              header-row-class-name="table-header"
              size="small"
            >
              <el-table-column
                prop="attr"
                :label="(form.category == 1 ? '设备' : '管段') + '属性'"
                align="center"
              >
                <template #default="scope">
                  <el-input
                    v-model="scope.row.attr"
                    placeholder="请输入设备属性、名称，例如：尺寸、材质"
                    maxlength="10"
                    show-word-limit
                    :disabled="
                      (scope.$index < 3 && form.category == 2) ||
                      (form.category == 1 &&
                        form.isCollection &&
                        scope.$index == 0) ||
                      !f_IsDelAttr(scope.$index)
                    "
                  />
                </template>
              </el-table-column>
              <el-table-column prop="type" label="属性数值/字段" align="center">
                <template #default="scope">
                  <div class="pr-[30px] pl-[30px]">
                    <el-select
                      v-model="scope.row.type"
                      placeholder="请选择属性"
                      :disabled="
                        (form.category == 1 &&
                          form.isCollection &&
                          scope.$index == 0) ||
                        (scope.$index < 3 && form.category == 2) ||
                        !f_IsDelAttr(scope.$index)
                      "
                    >
                      <el-option label="数值" :value="1" />
                      <el-option label="文本" :value="2" />
                      <el-option label="选项" :value="3" />
                      <el-option label="图片" :value="4" />
                    </el-select>
                  </div>
                  <i-ep-edit
                    v-if="scope.row.type == 3"
                    @click="f_EditOption(scope.$index)"
                    class="color-[#00a6ff] text-size-[11px] v-bottom float-right mt-[-18px] mr-[4px] cursor-pointer z-10"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="require" label="是否必填" align="center">
                <template #default="scope">
                  <el-switch
                    v-model="scope.row.require"
                    :disabled="scope.$index < 3 && form.category == 2"
                  />
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" width="120">
                <template #default="scope">
                  <el-button
                    type="danger"
                    size="small"
                    link
                    @click="f_Del(scope.$index)"
                    v-if="
                      (scope.$index > 2 &&
                        form.category == 2 &&
                        f_IsDelAttr(scope.$index)) ||
                      (form.category == 1 && f_IsDelAttr(scope.$index))
                    "
                    ><i-ep-delete
                      class="mr-[2px] text-size-[11px] v-bottom"
                    />删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
        <noneData
          :noneShow="
            (form.category == 1 && !pointData.length) ||
            (form.category == 2 && !lineData.length)
          "
          height="500"
        />
      </el-main>
    </el-container>
    <!-- 设备图例 -->
    <el-dialog
      v-model="dialogIcon.visible"
      title="设备图例"
      width="460px"
      append-to-body
      @close="f_CloseDialog"
      style="background: #fff"
      :close-on-click-modal="false"
      class="icon-dialog"
    >
      <el-row :gutter="10">
        <el-col
          :span="4"
          v-for="(item, index) in deviceIconData"
          @click="f_SelectIcon(item.id)"
          :key="item.id"
        >
          <div>
            <img
              v-if="index == 0"
              :src="deviceIcon1"
              class="device-icon menu"
            />
            <img
              v-if="index == 1"
              :src="deviceIcon2"
              class="device-icon menu"
            />
            <img
              v-if="index == 2"
              :src="deviceIcon3"
              class="device-icon menu"
            />
            <img
              v-if="index == 3"
              :src="deviceIcon4"
              class="device-icon menu"
            />
            <img
              v-if="index == 4"
              :src="deviceIcon5"
              class="device-icon menu"
            />
            <img
              v-if="index == 5"
              :src="deviceIcon6"
              class="device-icon menu"
            />
            <img
              v-if="index == 6"
              :src="deviceIcon7"
              class="device-icon menu"
            />
            <img
              v-if="index == 7"
              :src="deviceIcon8"
              class="device-icon menu"
            />

            <img
              v-if="index == 8"
              :src="deviceIcon9"
              class="device-icon menu"
            />
            <img
              v-if="index == 9"
              :src="deviceIcon10"
              class="device-icon menu"
            />
            <img
              v-if="index == 10"
              :src="deviceIcon11"
              class="device-icon menu"
            />

            <img
              v-if="index == 11"
              :src="deviceIcon12"
              class="device-icon menu"
            />
            <img
              v-if="index == 12"
              :src="deviceIcon13"
              class="device-icon menu"
            />
            <img
              v-if="index == 13"
              :src="deviceIcon14"
              class="device-icon menu"
            />
            <img
              v-if="index == 14"
              :src="deviceIcon15"
              class="device-icon menu"
            />
            <img
              v-if="index == 15"
              :src="deviceIcon16"
              class="device-icon menu"
            />
            <img
              v-if="index == 16"
              :src="deviceIcon17"
              class="device-icon menu"
            />
            <img
              v-if="index == 17"
              :src="deviceIcon18"
              class="device-icon menu"
            />
            <img
              v-if="index == 18"
              :src="deviceIcon19"
              class="device-icon menu"
            />
            <img
              v-if="index == 19"
              :src="deviceIcon20"
              class="device-icon menu"
            />
          </div>
          <div>{{ item.name }}</div>
        </el-col>
      </el-row>
    </el-dialog>

    <!-- 属性选项 编辑 -->
    <el-dialog
      v-model="dialogOption.visible"
      title="选项内容-编辑"
      width="600px"
      append-to-body
      @close="f_CloseDialog"
      style="background: #fff"
      :close-on-click-modal="false"
      class="icon-dialog bg-[#f5f5f5!important]"
    >
      <div class="p-[20px] bg-[#fff]">
        <el-table
          :data="attrOptionsData"
          border
          header-row-class-name="table-header"
        >
          <!-- v-model="
                  form.classAttribute[attrOptionsIndex].options[scope.$index]
                " -->
          <el-table-column prop="attr" label="选项值" align="center">
            <template #default="scope">
              <el-input
                v-model="attrOptionsData[scope.$index]"
                maxlength="20"
                show-word-limit
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="120">
            <template #default="scope">
              <el-button
                v-if="scope.$index == 0"
                type="primary"
                size="small"
                link
                @click="f_OptionAdd()"
                ><i-ep-plus
                  class="mr-[2px] text-size-[11px] v-bottom"
                />添加</el-button
              >
              <el-button
                v-if="
                  scope.$index != 0 &&
                  scope.$index != 1 &&
                  scope.$index > attrOptionsDataOld.length - 1
                "
                type="danger"
                size="small"
                link
                @click="f_OptionDel(scope.$index)"
                ><i-ep-delete
                  class="mr-[2px] text-size-[11px] v-bottom"
                />删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <div class="text-right mt-[15px]">
          <el-button type="primary" @click="f_ConfirmAddOptions">
            确 定
          </el-button>
        </div>
      </div>
    </el-dialog>
  </el-container>
</template>

<script setup lang="ts">
defineOptions({
  name: "Inspection",
  inheritAttrs: false,
});
import { find } from "lodash";
import { orderBy } from "lodash";
import { VueDraggableNext } from "vue-draggable-next";
import DeviceCategoryApi from "@/api/DeviceCategoryApi";
const loading = ref(false);
const currentIndex = ref(0);
const dialogIcon = reactive({
  visible: false,
});
const pointOrLine = ref("point");
const dialogOption = reactive({
  visible: false,
});
const form = reactive({
  className: "",
  pClassId: 0,
  category: 1,
  image: "",
  isCollection: false,
  classAttribute: [],
  colAttribute: [],
  classGisNo: " ",
});
const isDelDeviceCateGory = ref(true);
const attrUseStatuData = ref([]);
const attrOptionsIndex = ref(0);
const attrOptionsData = ref([]);
const attrOptionsDataOld = ref([]);
const activeMenu = ref("1-0");
const deviceIconData = ref([
  {
    id: 1,
    name: "w膜净水",
  },
  {
    id: 2,
    name: "二供",
  },
  {
    id: 3,
    name: "二供泵房",
  },
  {
    id: 4,
    name: "压力表",
  },
  {
    id: 5,
    name: "微型泵房",
  },
  {
    id: 6,
    name: "水厂",
  },
  {
    id: 7,
    name: "水房",
  },
  {
    id: 8,
    name: "水源井",
  },
  {
    id: 9,
    name: "水表",
  },
  {
    id: 10,
    name: "水质",
  },
  {
    id: 11,
    name: "水龄控制仪",
  },
  {
    id: 12,
    name: "流量计",
  },
  {
    id: 13,
    name: "消防栓",
  },
  {
    id: 14,
    name: "液位计",
  },
  {
    id: 15,
    name: "电动阀",
  },
  {
    id: 16,
    name: "直饮水",
  },
  {
    id: 17,
    name: "节水控制仪",
  },
  {
    id: 18,
    name: "调峰泵房",
  },
  {
    id: 19,
    name: "送水泵",
  },
  {
    id: 20,
    name: "通用设备",
  },
]);
// 左侧点击 管点
function f_ClickPointMenu(index: number) {
  pointOrLine.value = "point";
  currentIndex.value = index;
  form.classId = pointData.value[currentIndex.value].classId;
  form.id = pointData.value[currentIndex.value].id;
  form.className = pointData.value[currentIndex.value].className;
  form.pClassId = pointData.value[currentIndex.value].pClassId;
  form.category = pointData.value[currentIndex.value].category;
  form.image = pointData.value[currentIndex.value].image;
  form.isCollection = pointData.value[currentIndex.value].isCollection;
  form.classAttribute = pointData.value[currentIndex.value].classAttribute
    ? JSON.parse(
        JSON.stringify(pointData.value[currentIndex.value].classAttribute)
      )
    : [];
  // form.colAttribute = {};
  form.classGisNo = pointData.value[currentIndex.value].classGisNo;
  f_QueryAttrIsEdit();
}

// 左侧点击 管线
function f_ClickLineMenu(index: number) {
  pointOrLine.value = "line";
  currentIndex.value = index;
  form.classId = lineData.value[currentIndex.value].classId;
  form.id = lineData.value[currentIndex.value].id;
  form.className = lineData.value[currentIndex.value].className;
  form.pClassId = lineData.value[currentIndex.value].pClassId;
  form.category = lineData.value[currentIndex.value].category;
  form.image = lineData.value[currentIndex.value].image;
  form.isCollection = lineData.value[currentIndex.value].isCollection;
  form.classAttribute = lineData.value[currentIndex.value].classAttribute
    ? lineData.value[currentIndex.value].classAttribute
    : [];
  // form.colAttribute = {};
  form.classGisNo = lineData.value[currentIndex.value].classGisNo;
  f_QueryAttrIsEdit();
}

// 管点
const pointData = ref([]);

// 管线
const lineData = ref([]);

const deviceIcon1 = ref(
  new URL(`../../../assets/device/1.png`, import.meta.url).href
);
const deviceIcon2 = ref(
  new URL(`../../../assets/device/1.png`, import.meta.url).href
);
const deviceIcon3 = ref(
  new URL(`../../../assets/device/2.png`, import.meta.url).href
);
const deviceIcon4 = ref(
  new URL(`../../../assets/device/3.png`, import.meta.url).href
);
const deviceIcon5 = ref(
  new URL(`../../../assets/device/4.png`, import.meta.url).href
);
const deviceIcon6 = ref(
  new URL(`../../../assets/device/5.png`, import.meta.url).href
);
const deviceIcon7 = ref(
  new URL(`../../../assets/device/6.png`, import.meta.url).href
);
const deviceIcon8 = ref(
  new URL(`../../../assets/device/7.png`, import.meta.url).href
);
const deviceIcon9 = ref(
  new URL(`../../../assets/device/9.png`, import.meta.url).href
);
const deviceIcon10 = ref(
  new URL(`../../../assets/device/10.png`, import.meta.url).href
);
const deviceIcon11 = ref(
  new URL(`../../../assets/device/11.png`, import.meta.url).href
);
const deviceIcon12 = ref(
  new URL(`../../../assets/device/12.png`, import.meta.url).href
);
const deviceIcon13 = ref(
  new URL(`../../../assets/device/13.png`, import.meta.url).href
);
const deviceIcon14 = ref(
  new URL(`../../../assets/device/14.png`, import.meta.url).href
);
const deviceIcon15 = ref(
  new URL(`../../../assets/device/15.png`, import.meta.url).href
);
const deviceIcon16 = ref(
  new URL(`../../../assets/device/16.png`, import.meta.url).href
);
const deviceIcon17 = ref(
  new URL(`../../../assets/device/17.png`, import.meta.url).href
);
const deviceIcon18 = ref(
  new URL(`../../../assets/device/18.png`, import.meta.url).href
);
const deviceIcon19 = ref(
  new URL(`../../../assets/device/19.png`, import.meta.url).href
);
const deviceIcon20 = ref(
  new URL(`../../../assets/device/20.png`, import.meta.url).href
);

// 拖拽结束
function f_DragEndPoint() {
  let tempData = JSON.parse(JSON.stringify(pointData.value)).reverse();
  tempData.forEach((item, index) => {
    tempData[index].sort = index;
  });
  DeviceCategoryApi.api_batch_update_async(tempData).then(
    ({ data, errors, succeeded }) => {
      if (data) {
        ElMessage.success("更新成功！");
        currentIndex.value = 0;
        f_HandelQuery();
      } else {
        ElMessage.error("更新失败！");
      }
    }
  );
}

// 拖拽结束
function f_DragEndLine() {
  let tempData = JSON.parse(JSON.stringify(lineData.value)).reverse();
  tempData.forEach((item, index) => {
    tempData[index].sort = index;
  });
  DeviceCategoryApi.api_batch_update_async(tempData).then(
    ({ data, errors, succeeded }) => {
      if (data) {
        ElMessage.success("更新成功！");
        currentIndex.value = 0;
        f_HandelQuery();
      } else {
        ElMessage.error("更新失败！");
      }
    }
  );
}

// 查询 当前设备类型属性是否可以修改
function f_QueryAttrIsEdit() {
  let params = {
    pClassId: form.pClassId,
    classId: form.classId,
    data: [],
  };

  form.classAttribute.forEach((item) => {
    params.data.push({ attrName: item.attr });
  });

  DeviceCategoryApi.api_query_attr_is_edit(params).then(
    ({ data, errors, succeeded }) => {
      if (data) {
        attrUseStatuData.value = data;
        isDelDeviceCateGory.value = find(attrUseStatuData.value, { sta: true })
          ? false
          : true;
      } else {
        ElMessage.error(errors);
      }
    }
  );
}

// 是否可以删除属性
function f_IsDelAttr(rowIndex) {
  if (rowIndex < 0) return true;
  if (!form.id) {
    return true;
  }

  console.log(rowIndex);
  if (attrUseStatuData.value.length - 1 >= rowIndex) {
    return !attrUseStatuData.value[rowIndex].sta;
  } else {
    return true;
  }
}

// 提交数据
function f_HandleSubmit() {
  let params = Object.assign({}, form);
  if (!params.className) {
    ElMessage.error("请填写类型名称！");
    return;
  }
  if (!params.classAttribute.length) {
    ElMessage.error("设备属性至少一条！");
    return;
  }
  let msg = "";
  let attrArr = [];
  params.classAttribute.forEach((item) => {
    attrArr.push(item.attr);
    if (!item.attr) {
      msg = "属性名称不能为空！";
    }
  });
  if (msg) {
    ElMessage.error(msg);
    return;
  }

  if ([...new Set(attrArr)].length != attrArr.length) {
    ElMessage.error("属性名称不允许重复！");
    return;
  }

  params.classAttribute.forEach((item) => {
    if (item.type == 3 && item.options.length < 2) {
      msg = "最少设置两个选项内容";
    }
  });
  if (msg) {
    ElMessage.error(msg);
    return;
  }

  params.classAttribute.forEach((item) => {
    if (item.type == 3) {
      item.options.forEach((option) => {
        if (!option.length) {
          msg = "选项不能为空！";
        }
      });
    }
  });
  if (msg) {
    ElMessage.error(msg);
    return;
  }
  params.image = String(params.image);
  params.category = String(params.category);
  if (params.id) {
    params.classId = params.classId;
    DeviceCategoryApi.api_update(params).then(({ data, errors, succeeded }) => {
      if (data) {
        ElMessage.success("编辑成功！");
        f_HandelQuery();
      } else {
        ElMessage.error("该选项已经产生数据，无法删除，也无法编辑！");
      }
    });
  } else {
    params.classId = params.classId;
    DeviceCategoryApi.api_add(params).then(({ data, errors, succeeded }) => {
      if (succeeded) {
        ElMessage.success("新增成功！");
        f_HandelQuery();
      } else {
        ElMessage.error(errors);
      }
    });
  }
}

// 查询
function f_HandelQuery() {
  loading.value = true;
  const params1 = {
    pageSize: 100,
    pageIndex: 1,
    pClassId: "01",
  };
  const params2 = {
    pageSize: 100,
    pageIndex: 1,
    pClassId: "02",
  };
  DeviceCategoryApi.api_query(params1).then(({ data, errors, succeeded }) => {
    if (succeeded) {
      if (data.items) {
        pointData.value = orderBy(data.items, ["sort"], ["desc"]);
        if (form.category == 1 && pointData.value.length) {
          form.className = pointData.value[currentIndex.value].className;
          form.pClassId = pointData.value[currentIndex.value].pClassId;
          form.category = pointData.value[currentIndex.value].category;
          form.image = pointData.value[currentIndex.value].image;
          form.isCollection = pointData.value[currentIndex.value].isCollection;
          // form.classAttribute = [];
          form.classAttribute = pointData.value[currentIndex.value]
            .classAttribute
            ? pointData.value[currentIndex.value].classAttribute
            : [];
          form.colAttribute = {};
          form.classGisNo = pointData.value[currentIndex.value].classGisNo;
          form.id = pointData.value[currentIndex.value].id;

          activeMenu.value =
            pointData.value[currentIndex.value].category +
            "-" +
            currentIndex.value;
          f_QueryAttrIsEdit();
        }
      } else {
        if (form.category == 1) {
          pointData.value = [];
          form.className = "";
          form.pClassId = 0;
          form.category = 1;
          form.image = "";
          form.isCollection = false;
          form.classAttribute = [];
          form.colAttribute = {};
          form.classGisNo = "";
          form.id = 0;
        }
      }
    }
    loading.value = false;
  });
  DeviceCategoryApi.api_query(params2).then(({ data, errors, succeeded }) => {
    loading.value = false;
    if (data.items) {
      lineData.value = orderBy(data.items, ["sort"], ["desc"]);
      if (form.category == 2 && lineData.value.length) {
        form.className = lineData.value[currentIndex.value].className;
        form.pClassId = lineData.value[currentIndex.value].pClassId;
        form.category = lineData.value[currentIndex.value].category;
        form.image = lineData.value[currentIndex.value].image;
        form.isCollection = lineData.value[currentIndex.value].isCollection;
        // form.classAttribute = [];
        form.classAttribute = lineData.value[currentIndex.value].classAttribute
          ? lineData.value[currentIndex.value].classAttribute
          : [];
        form.colAttribute = {};
        form.classGisNo = lineData.value[currentIndex.value].classGisNo;
        form.id = lineData.value[currentIndex.value].id;

        activeMenu.value =
          lineData.value[currentIndex.value].category +
          "-" +
          currentIndex.value;

        f_QueryAttrIsEdit();
      }
    } else {
      if (form.category == 2) {
        pointData.value = [];
        form.className = "";
        form.pClassId = 0;
        form.category = 1;
        form.image = "";
        form.isCollection = false;
        form.classAttribute = [];
        form.colAttribute = {};
        form.classGisNo = "";
        form.id = 0;
      }
    }
  });
}

// 是否采集
function f_ChangeIsCollection() {
  if (form.isCollection) {
    form.classAttribute.unshift({
      attr: "数据采集编号",
      type: 1, // 1数字 2文本 3图片 4选项
      value: "",
      require: true,
      options: [],
    });
  } else {
    form.classAttribute.splice(0, 1);
  }
}

// 编辑属性选项
function f_EditOption(index) {
  attrOptionsIndex.value = index;
  if (!form.classAttribute[index].options.length) {
    form.classAttribute[index].options = ["选项1", "选项2"];
  }
  attrOptionsData.value = JSON.parse(
    JSON.stringify(form.classAttribute[attrOptionsIndex.value].options)
  );
  if (pointOrLine.value == "point") {
    if (
      attrOptionsIndex.value >
      pointData.value[currentIndex.value].classAttribute.length - 1
    ) {
      attrOptionsDataOld.value = [];
    } else {
      attrOptionsDataOld.value = JSON.parse(
        JSON.stringify(
          pointData.value[currentIndex.value].classAttribute[
            attrOptionsIndex.value
          ].options
        )
      );
    }
  } else {
    if (
      attrOptionsIndex.value >
      lineData.value[currentIndex.value].classAttribute.length - 1
    ) {
      attrOptionsDataOld.value = [];
    } else {
      attrOptionsDataOld.value = JSON.parse(
        JSON.stringify(
          lineData.value[currentIndex.value].classAttribute[
            attrOptionsIndex.value
          ].options
        )
      );
    }
  }

  dialogOption.visible = true;
}

// 编辑属性选项 确认
function f_ConfirmAddOptions() {
  form.classAttribute[attrOptionsIndex.value].options = attrOptionsData.value;
  f_CloseDialog();
}

// 返回图片
function f_GetPath(index: number) {
  return new URL("../../../assets/device/" + index + ".png", import.meta.url)
    .href;
}

// 选择图片
function f_SelectIcon(index: number) {
  form.image = index;
  console.log(form.image);
  dialogIcon.visible = false;
}

// 打开弹框选择图片
function f_SelectIconOpen() {
  dialogIcon.visible = true;
}

// 关闭弹框
function f_CloseDialog() {
  dialogIcon.visible = false;
  dialogOption.visible = false;
}

// 添加设备属性
function f_Add() {
  form.classAttribute.push({
    attr: "",
    type: 1, // 1数字 2文本 3图片 4选项
    value: "",
    require: true,
    options: [],
  });
}

// 删除设备属性
function f_Del(index: number) {
  form.classAttribute.splice(index, 1);
}

// 添加管点
function f_AddPoint() {
  if (!form.id && pointData.value.length) {
    ElMessage.error(
      "请先保存" + (form.category == 1 ? "设备" : "管段") + "类型!"
    );
    return;
  }
  pointData.value.push({
    className: "请输入设备名称",
    pClassId: "01",
    category: 1,
    image: 1,
    isCollection: false,
    classAttribute: [
      {
        attr: "",
        type: 1, // 1数字 2文本 3图片 4选项
        value: "",
        require: true,
        options: [],
      },
    ],
    colAttribute: "",
    classGisNo: "",
    id: 0,
  });
  activeMenu.value = "1-" + (pointData.value.length - 1);
  isDelDeviceCateGory.value = true;
  f_ClickPointMenu(pointData.value.length - 1);
}

// 添加管线
function f_AddLine() {
  if (!form.id && lineData.value.length) {
    ElMessage.error(
      "请先保存" + (form.category == 1 ? "设备" : "管段") + "类型!"
    );
    return;
  }
  lineData.value.push({
    className: "请输入管段名称",
    pClassId: "02",
    category: 2,
    image: "",
    isCollection: false,
    classAttribute: [
      {
        attr: "管径",
        type: 3, // 1数字 2文本 3图片 4选项
        value: "",
        require: true,
        options: ["管径1", "管径2"],
      },
      {
        attr: "口径",
        type: 3, // 1数字 2文本 3图片 4选项
        value: "",
        require: true,
        options: ["口径1", "口径2"],
      },
      {
        attr: "管材",
        type: 3, // 1数字 2文本 3图片 4选项
        value: "",
        require: true,
        options: ["管材1", "管材2"],
      },
    ],
    colAttribute: {},
    classGisNo: "",
    id: 0,
  });

  activeMenu.value = "2-" + (lineData.value.length - 1);
  isDelDeviceCateGory.value = true;
  f_ClickLineMenu(lineData.value.length - 1);
}

// 添加 选项
function f_OptionAdd() {
  // form.classAttribute[attrOptionsIndex.value].options.push("");
  attrOptionsData.value.push("");
}

// 删除选项
function f_OptionDel(index: number) {
  // form.classAttribute[attrOptionsIndex.value].options.splice(index, 1);
  attrOptionsData.value.splice(index, 1);
}

// 删除
function f_HandleDel() {
  ElMessageBox.confirm("确认删除数据?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      DeviceCategoryApi.api_del({ id: form.id }).then(
        ({ data, errors, succeeded }) => {
          if (data) {
            ElMessage.success("删除成功！");
            currentIndex.value = 0;
            f_HandelQuery();
          } else {
            ElMessage.error("该选项已经产生数据，无法删除，也无法编辑！");
          }
        }
      );
    })
    .catch(() => ElMessage.info("已取消删除!"));
}

onMounted(() => {
  f_HandelQuery();
});
</script>
<style scoped lang="scss">
.icon-dialog {
  .el-row {
    padding: 20px;

    .el-col {
      margin-bottom: 8px;
      cursor: pointer;

      img {
        height: 50px;
        padding: 10px;
        border: 1px solid #dedede;
        border-radius: 4px;
      }

      div {
        font-size: 12px !important;
        text-align: center;
      }
    }
  }
}

:deep .el-menu {
  height: calc(100% - 40px);
  border: none;
}

.add {
  padding-bottom: 10px;
  text-align: left;
  border-bottom: 1px dashed #dcdcdc;

  :deep .el-tag {
    height: 20px;
    padding: 4px 20px !important;
    font-size: 12px;
    cursor: pointer;
  }
}

:deep .el-sub-menu__title:hover {
  background-color: transparent !important;
}

:deep .el-menu-item:hover {
  background-color: #f5f5f5 !important;
}

.title {
  padding-bottom: 12px;
  color: #32bebd;
  border-bottom: 1px dashed #dcdcdc;
}

.device-icon {
  height: 34px;
  padding: 3px;
  cursor: pointer;
  border: 1px solid #eee;
  border-radius: 4px;
}

.device-icon.menu {
  height: 26px;
  margin-top: -3px;
  vertical-align: top;
  border: none;

  background: #03a9f43b;
  border-radius: 3px;
  padding: 2px;
  margin-right: 4px;
}

:deep .el-color-picker--small .el-color-picker__trigger {
  width: 100px;
}
.linePoint {
  height: 12px;
  width: 20px;
  display: inline-block;
  background: red;
  margin-top: 0px;
  margin-right: 4px;
  border-radius: 2px;
}
</style>
